/**
 * 
 */
package com.ifast.common.utils.alioss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/** 
 * 项目名称：afast
 * 类名称：GetProgressSample
 * 类描述： 
 * 创建人：Administrator 
 * 创建时间：2017年6月9日 上午9:38:28
 * 修改人：Administrator 
 * 修改时间：2017年6月9日 上午9:38:28
 * 修改备注： 
 * @version 
 */
@Slf4j
public class GetProgressUtil {
	/**
     * 获取上传进度回调
     */
    static class PutObjectProgressListener implements ProgressListener {

        private long bytesWritten = 0;
        private long totalBytes = -1;
        private boolean succeed = false;
//        private IRedisParentService redisParentService = (IRedisParentService)ContextHolderUtils.getApplicationContext().getBean("redisParentService");
        
        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            /*Manager manc = ClientManage.getManager();
            String uuId = ClientManage.getClient().getId()+ClientManage.getClient().getIp();*/
            
            switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.info("Start to upload......");
               /* if(manc.getId() != null){
                	ProcessMsg pm = new ProcessMsg(0, 0,"上传开始");
                	String listRedisStr = JacksonJsonUtil.toJSon(pm);
//        			redisParentService.cacheValue(uuId, listRedisStr, 120L);
                }*/
                break;
            
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                log.info(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                /*if (this.totalBytes != -1) {
                    int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
                    ProcessMsg pm = new ProcessMsg(0, percent,"上传中");
                    String listRedisStr = JacksonJsonUtil.toJSon(pm);
//        			redisParentService.cacheValue(uuId, listRedisStr, 120L);
                } else {
                    log.info(bytes + " bytes have been written at this time, upload ratio: unknown" +
                           "(" + this.bytesWritten + "/...)");
                }*/
                break;
                
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                log.info("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
               /* ProcessMsg pm = new ProcessMsg(1,100,"上传成功");
                String listRedisStr = JacksonJsonUtil.toJSon(pm);
//    			redisParentService.cacheValue(uuId, listRedisStr, 120L);*/
                break;
                
            case TRANSFER_FAILED_EVENT:
               /* log.info("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                ProcessMsg pm1 = new ProcessMsg(1,100,"上传失败!");
                String listRedisStr1 = JacksonJsonUtil.toJSon(pm1);*/
//    			redisParentService.cacheValue(uuId, listRedisStr1, 120L);
                break;
                
            default:
                break;
            }
        }

        public boolean isSucceed() {
            return succeed;
        }
    }
    
    /**
     * 获取下载进度回调
     */
    static class GetObjectProgressListener implements ProgressListener {
        
        private long bytesRead = 0;
        private long totalBytes = -1;
        private boolean succeed = false;
        
        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.info("Start to download......");
                break;
            
            case RESPONSE_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                log.info(this.totalBytes + " bytes in total will be downloaded to a local file");
                break;
            
            case RESPONSE_BYTE_TRANSFER_EVENT:
                this.bytesRead += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int)(this.bytesRead * 100.0 / this.totalBytes);
                    log.info(bytes + " bytes have been read at this time, download progress: " +
                            percent + "%(" + this.bytesRead + "/" + this.totalBytes + ")");
                } else {
                    log.info(bytes + " bytes have been read at this time, download ratio: unknown" +
                            "(" + this.bytesRead + "/...)");
                }
                break;
                
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                log.info("Succeed to download, " + this.bytesRead + " bytes have been transferred in total");
                break;
                
            case TRANSFER_FAILED_EVENT:
                log.info("Failed to download, " + this.bytesRead + " bytes have been transferred");
                break;
                
            default:
                break;
            }
        }
        
        public boolean isSucceed() {
            return succeed;
        }
    }
    
    public static void main(String[] args) { 
        String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
        String accessKeyId = "LTAIzOLc3cR9EwEf";
        String accessKeySecret = "bGl5HMpzh1TVQJeibjfWYXxusOtMzQ";
        String bucketName = "hongshanpic";
        
        String key = "object-get-progress-sample";
        
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            File fh = createSampleFile();
            
            // 带进度条的上传 
            client.putObject(new PutObjectRequest(bucketName, key, fh).
                    <PutObjectRequest>withProgressListener(new PutObjectProgressListener()));
            
            // 带进度条的下载
            client.getObject(new GetObjectRequest(bucketName, key).
                    <GetObjectRequest>withProgressListener(new GetObjectProgressListener()), fh);
            
        } catch (Exception e) {
        	log.error(e.getMessage());
        }
    }
    
    
    /**
     * 创建一个临时文件
     * 
     */
    private static File createSampleFile() throws IOException {
        File file = File.createTempFile("oss-java-sdk-", ".txt");
        file.deleteOnExit();

        Writer writer = null;
        FileOutputStream fio = null;
        try {
        	fio = new FileOutputStream(file);
        	writer = new OutputStreamWriter(fio);
        	fio.close();
        	for (int i = 0; i < 1000; i++) {
               writer.write("abcdefghijklmnopqrstuvwxyz\n");
               writer.write("0123456789011234567890\n");
            }
            writer.close();
		} catch (IOException e) {
			log.error(e.getMessage());
		}finally{
			if(fio != null){
				fio.close();
			}
		}
        return file;
    }
}
